//
//  PSScore.m
//  PrefCore
//
//  Created by Sergey on 2/28/14.
//  Copyright (c) 2014 Play-on-smart. All rights reserved.
//

#import "PSScore.h"
#import "PSGame.h"

@interface PSScoreValues () {
    NSMutableArray *_history;
}

@end

@implementation PSScoreValues

-(instancetype)init {
    if (self = [super init]) {
        _history = [NSMutableArray array];
    }
    return self;
}

-(NSArray*)history {
    return _history;
}

-(void)reset {
    _isChanged = NO;
    _current = 0;
    [_history removeAllObjects];
}

-(void)settle {
    _isChanged = NO;
}

-(void)addValue:(PSScoreValue)value {
    if (!value) {
        return;
    }
    // Add to history only once.
    // In Rostov current can be 0 in mountain and it must be shown.
    if (!_isChanged && (_history.count || _current)) {
        [_history addObject:[NSNumber numberWithLongLong:_current]];
    }
    _isChanged = YES;
    _current += value;
}

@end

@implementation PSClosableValues

-(instancetype)init {
    if (self = [super init]) {
        _delta = 0;
    }
    return self;
}

-(void)reset {
    [super reset];
    _delta = 0;
}

-(PSScoreValue)eventual {
    return self.current + _delta;
}

@end

@implementation PSScoreBalance

-(instancetype)init {
    if (self = [super init]) {
        _current = 0;
        _delta = 0;
    }
    return self;
}

-(void) reset {
    _current = 0;
    _delta = 0;
}

@end

@implementation PSScorePool

@end

@interface PSScore () {
    PSClosableValues *_whists[PS_GAME_PLAYERS];
}

@end

@implementation PSScore

-(instancetype)init {
    if (self = [super init]) {
        _balance = [[PSScoreBalance alloc] init];
        _pool = [[PSScorePool alloc] init];
        _mountain = [[PSClosableValues alloc] init];
        for (int i = 0 ; i != PS_GAME_PLAYERS ; i++) {
            _whists[i] = [[PSClosableValues alloc] init];
        }
    }
    return self;
}

-(PSClosableValues* __strong *) whists {
    return _whists;
}

-(void) settle {
    [_mountain settle];
    [_pool settle];
    for (int i = 0 ; i != PS_GAME_PLAYERS ; i++) {
        [_whists[i] settle];
    }
}

-(void) reset {
    [_balance reset];
    [_mountain reset];
    [_pool reset];
    for (int i = 0 ; i != PS_GAME_PLAYERS ; i++) {
        [_whists[i] reset];
    }
}

-(NSString*) description {
    NSMutableString *res = [NSMutableString string];
    [res appendFormat:@"[M:%lld,P:%lld,W:"
    ,   _mountain.current
    ,   _pool.current
    ];
    for (int i = 0 ; i != PS_GAME_PLAYERS ; i++) {
        if (i) {
            [res appendString:@","];
        }
        [res appendFormat:@"%lld", _whists[i].current];
    }
    [res appendString:@"]"];
    return [res copy];
}

@end


